package com.app.newiptv.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.app.newiptv.R;
import com.app.newiptv.adaper.VodAdaper;
import com.app.newiptv.adaper.VodItemAdapter;
import com.app.newiptv.base.MyApplication;
import com.app.newiptv.presenter.VodPresenter;
import com.app.newiptv.utils.Paths;
import com.app.newiptv.view.FocusGridLayoutManager;
import com.app.newiptv.view.MyRecycleView;

import java.io.IOException;


public class VodActivity extends Activity implements VodPresenter.Callback {
    private MyRecycleView vodRecycleView; // 左侧菜单
    private MyRecycleView itemrecycleview;
    private VodPresenter vodPresenter;
    private int LOAD_LIST_COMPLETE = 1;
    private int LOAD_ITEM_COMPLETE = 2;
    private VodAdaper vodAdaper;
    private VodItemAdapter vodItemAdapter;
    public static int focusPosition;
    private String url;
    private TextView text_allmovie;
    private Button pageUp;
    private Button pageUpBottom;
    private Button pageDownBottom;
    private Button pageDown;
    public TextView select_position;
    private ImageView focusView;
    View mSearchItemView;
    public int page = 1;
    public static int index;
    private Handler mainHandler;

    String bigType;
    String type;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == LOAD_LIST_COMPLETE) { // 左侧菜单数据
                VodPresenter presenter = (VodPresenter) msg.obj;
                int count = msg.arg1;
                onBindData(presenter, count);
                if (hasMessages(LOAD_LIST_COMPLETE)) {
                    removeMessages(LOAD_LIST_COMPLETE);
                }
            } else if (msg.what == LOAD_ITEM_COMPLETE) { // 右侧列表数据.
                VodPresenter presenter = (VodPresenter) msg.obj;
                int count = msg.arg1;
                onBindItem(presenter, count);
                String menuName = vodAdaper.getMeunName(focusPosition);
                text_allmovie.setText("共" + count +"影片"+"(" + menuName + ")");
                select_position.setText((index+1)+"/"+count);
//                try {
//                    Runtime.getRuntime().exec("input keyevent 22");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                itemrecycleview.requestFocus();
                if (hasMessages(LOAD_ITEM_COMPLETE)) {
                    removeMessages(LOAD_ITEM_COMPLETE);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vod);
//        Bundle bundle = getIntent().getBundleExtra("bundle");
//        url = bundle.getString("menuUrl");
        Intent intent = getIntent();
         bigType = intent.getStringExtra("type_big_id");
         type = intent.getStringExtra("type_id");
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        initData();
    }

    private void initView() {
        vodRecycleView = (MyRecycleView) this.findViewById(R.id.vod_recycle);
        itemrecycleview = (MyRecycleView) this.findViewById(R.id.vod_recycle_view);
        text_allmovie = (TextView) findViewById(R.id.text_allmovie);
        select_position = (TextView) findViewById(R.id.select_position);
        focusView = (ImageView) findViewById(R.id.focus_view);
        text_allmovie.setTypeface(MyApplication.face);
        mSearchItemView = findViewById(R.id.serch_item);
        pageUp = (Button) findViewById(R.id.page_up);
        pageUpBottom = (Button) findViewById(R.id.page_up_bottom);
        pageDown = (Button) findViewById(R.id.page_down);
        pageDownBottom = (Button) findViewById(R.id.page_down_bottom);
        pageUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (page>1){
                    page = page - 1;
                }else {
                    page = 1;
                }
                vodPresenter.loadPageVodItem(page);
            }
        });
        pageUpBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (page>1){
                    page = page - 1;
                }else {
                    page = 1;
                }
                vodPresenter.loadPageVodItem(page);
            }
        });
        pageDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = page + 1;
                vodPresenter.loadPageVodItem(page);

            }
        });
        pageDownBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = page + 1;
                vodPresenter.loadPageVodItem(page);

            }
        });
//        pageUp.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View view, boolean b) {
//                if (b) {
//                    view.bringToFront();
//                    view.animate().scaleX(1.50f);
//                    view.animate().scaleY(1.50f);
//                } else {
//                    view.animate().scaleX(1.0f);
//                    view.animate().scaleY(1.0f);
//                }
//            }
//        });
//        pageDown.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View view, boolean b) {
//                if (b) {
//                    view.bringToFront();
//                    view.animate().scaleX(1.50f);
//                    view.animate().scaleY(1.50f);
//                } else {
//                    view.animate().scaleX(1.0f);
//                    view.animate().scaleY(1.0f);
//                }
//            }
//        });
        //
        mSearchItemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    view.bringToFront();
                    view.animate().scaleX(1.50f);
                    view.animate().scaleY(1.50f);
                } else {
                    view.animate().scaleX(1.0f);
                    view.animate().scaleY(1.0f);
                }
            }
        });
        mSearchItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(VodActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onBackPressed() {
        focusPosition = 0;
        index = 0;
        page = 0;
        super.onBackPressed();
    }

    private void initData() {
        vodPresenter = new VodPresenter(this);
        vodPresenter.setBigType(bigType);
        vodPresenter.setDisplayed(true);
        // http://newlive.qixun.tv:89/inc/apijson.php?ac=type
//        bigType = "9";
        vodPresenter.loadItem(Paths.HOSTPATH + Paths.CHANNEL_TYPES, this);
        // TODO:hailon.qiu
//        vodPresenter.loadItem("http://newlive.qixun.tv:89/inc/apijson.php?ac=type", this);
        vodRecycleView.setOnKeyListener(new VodMenuOnKey());
        vodRecycleView.setNextFocusRightId(R.id.vod_recycle_view);
    }

    /**
     * 绑定左侧菜单数据
     * @param presenter
     * @param count
     */
    public void onBindData(VodPresenter presenter, int count) {
//        presenter.setBigType(bigType);
        vodAdaper = new VodAdaper(presenter);
        vodAdaper.setCount(count);
        vodRecycleView.setLayoutManager(new FocusGridLayoutManager(this, 1));
        vodRecycleView.setAdapter(vodAdaper);
        vodRecycleView.requestFocus();
        vodRecycleView.post(new Runnable() {
            @Override
            public void run() {
                if (vodRecycleView.getChildCount() > focusPosition) {
                    vodAdaper.selected();
                }
            }
        });
        vodRecycleView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (vodRecycleView.getChildCount() > focusPosition) {
                        vodAdaper.selected();
                    }
                    page = 1;
                }
            }
        });
    }

    /**
     * 绑定右侧的item数据.
     */
    public void onBindItem(VodPresenter presenter, int count) {
        vodItemAdapter = new VodItemAdapter(presenter, this,focusView);
        vodItemAdapter.setCount(count);
        vodItemAdapter.setMainHandler(handler);
//        vodItemAdapter.
        itemrecycleview.setLayoutManager(new FocusGridLayoutManager(this, 5));
        itemrecycleview.setAdapter(vodItemAdapter);
        itemrecycleview.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (itemrecycleview.getChildCount() > 0) {
                        itemrecycleview.getChildAt(0).requestFocus();
                        //Toast.makeText(VodActivity.this, "item获取到焦点", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    public void onError(int code, String msg) {

    }

    /**
     * 左侧菜单数据加载
     * @param presenter
     * @param count
     */
    @Override
    public void onMovieCompleted(VodPresenter presenter, int count) {
        Message msg = Message.obtain();
        msg.arg1 = count;
        msg.what = LOAD_LIST_COMPLETE;
        msg.obj = presenter;
        handler.sendMessage(msg);
    }

    /**
     * 右侧列表数据加载
     */
    @Override
    public void onVodLoadCompleted(VodPresenter presenter, int count) {
        Message msg = Message.obtain();
        msg.arg1 = count;
        msg.what = LOAD_ITEM_COMPLETE;
        msg.obj = presenter;
        handler.sendMessage(msg);
    }

    @Override
    public void onDetailCompleted(VodPresenter presenter) {
        presenter.onBindDetailData(viewHolder);
    }

    private VodPresenter.IDetailDataViewHolder viewHolder = new VodPresenter.IDetailDataViewHolder() {
        @Override
        public void setNameAndCount(String name, String count) {
            text_allmovie.setText("" + name + count + "部（最新上线）");
        }
    };

    public class VodMenuOnKey implements View.OnKeyListener {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            int action = event.getAction();
            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                if (action == KeyEvent.ACTION_DOWN) {
                    if (vodAdaper != null) {
                        focusPosition = vodAdaper.selectedNext(); // 下面是否有item
                        //Toast.makeText(VodActivity.this, "下==》：" + focusPosition, Toast.LENGTH_SHORT).show();
                    }
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                if (action == KeyEvent.ACTION_UP) {
                    if (vodAdaper != null) {
                        focusPosition = vodAdaper.selectedPre();
                        //Toast.makeText(VodActivity.this, "上==》：" + focusPosition, Toast.LENGTH_SHORT).show();
                    }
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {
                return true;
            }
            return false;
        }
    }
}
